package com.hihonor.db;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.db.dialect.DriverUtil;
import cn.hutool.log.Log;
import com.hihonor.Main;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * @author 李志雄
 * @since 2023-10-14
 */
public class JdbcTest {
    private static final Log log = Log.get();

    public static final String TEST_SQL_MYSQL = "select 1";

    public static final String TEST_SQL_ORACLE = "select 1 from dual";

    private static String driveClass;


    private JdbcTest() {
    }

    public static String getDriveClass(String url) {
        // 自动识别驱动名称
        driveClass = DriverUtil.identifyDriver(url);
        return driveClass;
    }

    public static String getTestSql(String url) {
        if (CharSequenceUtil.isEmpty(driveClass)) {
            driveClass = DriverUtil.identifyDriver(url);
        }
        return driveClass.contains("oracle") ? TEST_SQL_ORACLE : TEST_SQL_MYSQL;
    }

    public static String getTestSql(Connection connection) {
        if (CharSequenceUtil.isEmpty(driveClass)) {
            driveClass = DriverUtil.identifyDriver(connection);
        }
        return driveClass.contains("oracle") ? TEST_SQL_ORACLE : TEST_SQL_MYSQL;
    }

    /**
     * 测试连接是否通
     *
     * @param main
     * @param jdbcUrl
     * @param user
     * @param pass
     * @return
     */
    public static boolean testConnect(Main main, String jdbcUrl, String user, String pass) {
        ResultSet resultSet = null;
        Statement statement = null;
        Connection conn = null;
        try {
            Class.forName(getDriveClass(jdbcUrl));
            conn = DriverManager.getConnection(jdbcUrl, user, pass);
            statement = conn.createStatement();
            resultSet = statement.executeQuery(getTestSql(jdbcUrl));
            if (resultSet.next()) {
                main.showSuccessMsg("连接成功！");
                return true;
            }
            main.showFailMsg("连接失败！");
            return false;
        } catch (Exception e) {
            log.error(e.getMessage());
            main.showFailMsg("连接失败！");
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            try {
                if (statement != null) {
                    statement.close();
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        return false;
    }
}
